package com.sdy.rc.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.rc.biz.service.MaterialsLibraryService;
import com.sdy.rc.biz.service.TMatterService;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.fs.api.FsApi;
import com.sdy.rc.biz.model.MaterialsLibrary;
import com.sdy.common.model.FileObj;
import com.sdy.common.model.Response;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import com.sdy.mvc.controller.BaseController;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cgj
 * @since 2019-09-27
 */
@Slf4j
@Controller
@RequestMapping("/materialsLibrary")
public class MaterialsLibraryController extends BaseController {
    @Autowired
    private MaterialsLibraryService materialsLibraryService;
    @Autowired
	private TMatterService tMatterService;
    @Autowired
    private FsApi fsApi;
    
    @Value("${file.upload.url}")
	private String filePath;
    
    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Response upload(MultipartFile file) throws Exception {
    	log.info("进入--upload");
        FileObj fileObj = fsApi.uploadFile(ArrayUtils.toObject(file.getBytes()), file.getOriginalFilename(), null);
        log.info("fileObj--"+fileObj);
        return Response.success(fileObj);
    }
    
    //文件名称list
    @GetMapping("/uploadFilesList")
    @ResponseBody
    public List<FileObj> uploadFilesList(Integer id) {
    	/*String[] id = materialsListLocal.split(";");
    	List<Integer> list = new ArrayList<>();
    	for (int i = 0; i < id.length; i++) {
    		int idInt = Integer.valueOf(id[i]);
    		list.add(idInt);
		}*/
    	String uploadFiles= materialsLibraryService.getById(id).getUploadFiles();
    	String[] uploadFileId = uploadFiles.split(",");
    	List<String> list = new ArrayList<>();
    	for (int i = 0; i < uploadFileId.length; i++) {
    		String idInt = uploadFileId[i];
    		list.add(idInt);
		}
        log.info("fsApi.getFileListInfo(list)--"+ fsApi.getFileListInfo(list));
        return fsApi.getFileListInfo(list);
    }

    /**
     * 页面
     */
    @GetMapping("/page")
    public String page() {
        return "/page/materials_library/page";
    }

    /**
     * 新建页面
     */
    @GetMapping("/newPage")
    public String newPage(Model model) {
    	log.info("进入NewPage");
    	log.info("filePath--"+filePath);
    	model.addAttribute("filePath", filePath);
    	model.addAttribute("param",new MaterialsLibrary());
        return "/page/materials_library/new";
    }
    
    /**
     * 上传材料详情
     */
    @GetMapping("/imgDetail")
    @ResponseBody
    public Response imgDetail(String materialsListLocal) {
        LambdaQueryWrapper<MaterialsLibrary> lqwml = new LambdaQueryWrapper<>();
        lqwml.eq(MaterialsLibrary::getUploadFiles, materialsListLocal);
        MaterialsLibrary materialsLibrary = materialsLibraryService.getOne(lqwml);
        return Response.success(materialsLibrary);
    }
    
    /**
     * 详情页面
     */
    @GetMapping("/detailPage")
    public String detailPage(Model model, Integer id) {
        model.addAttribute("param", materialsLibraryService.getById(id));
        return "/page/materials_library/detail";
    }
    
    /**
     * 修改页面
     */
    @GetMapping("/updatePage")
    public String updatePage(Model model, Integer id) {
        model.addAttribute("param", materialsLibraryService.getById(id));
        return "/page/materials_library/update";
    }

    /**
     * 分页数据
     * @param request
     * @param page [current, size]
     * @return
     */
    @GetMapping("/pageData")
    @ResponseBody
    public Response pageData(HttpServletRequest request, Page<MaterialsLibrary> page) {
        QueryWrapper<MaterialsLibrary> wrapper = new QueryWrapper<>();

        String id = request.getParameter("id");
        wrapper.eq(StringUtil.isNotBlank(id), "id", id);

        String key = request.getParameter("key");
        wrapper.eq(StringUtil.isNotBlank(key), "id", key);

        String createTime = request.getParameter("createTime");
        if (StringUtil.isNotBlank(createTime)) {
            wrapper.between("create_time",
                DateUtil.getDate(createTime + " 00:00:00", DateUtil.DATETIME_FORMAT),
                DateUtil.getDate(createTime + " 23:59:59", DateUtil.DATETIME_FORMAT));
        }

        String createTimeRange = request.getParameter("createTimeRange");
        if (StringUtil.isNotBlank(createTimeRange)) {
            String[] timeRangeStrs = createTimeRange.split(" - ");
            wrapper = wrapper.between("create_time",
                    DateUtil.getDate(timeRangeStrs[0], DateUtil.DATETIME_FORMAT),
                    DateUtil.getDate(timeRangeStrs[1], DateUtil.DATETIME_FORMAT));
        }

        wrapper.orderByDesc("id");

        IPage<MaterialsLibrary> result = materialsLibraryService.page(page, wrapper);
        return Response.success(result);
    }

    /**
     * 保存数据
     * @param
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public Response save(MaterialsLibrary materialsLibrary) {
    	Boolean i = materialsLibraryService.save(materialsLibrary);
    	if(!i) {
    		log.info("新增材料失败");
    		Response.error();
    	}
    	Integer id = materialsLibrary.getId();
    	log.info("id--"+id);
        return Response.success(id);
    }

    /**
     * 更新数据
     * @param
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public Response update(MaterialsLibrary materialsLibrary) {
    	log.info("进入update--");
    	Boolean i = materialsLibraryService.updateById(materialsLibrary);
    	if(!i) {
    		log.info("修改材料失败");
    		Response.error();
    	}
    	Integer id = materialsLibrary.getId();
    	log.info("id--"+id);
    	materialsLibraryService.updateById(materialsLibrary);
        return Response.success(id);
    }

    /**
     * 删除数据
     * @param id 主键
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    public Response delete(Integer id) {
        return Response.success(materialsLibraryService.removeById(id));
    }

    /**
     * 删除数据
     * @param id 主键
     * @return
     */
    @GetMapping("/deleteBatch")
    @ResponseBody
    public Response deleteBatch(Integer[] id) {
        if (id != null) {
            materialsLibraryService.removeByIds(Arrays.asList(id));
        }
        return Response.success();
    }
}
